﻿using System;
using System.IO;

namespace WPFEdit.Util
{
    public static class IOUtils
    {
		/// <summary>
		/// Loads an object from an XML file using the specified path and type.
		/// </summary>
        public static object DeserialzeXmlFile(String path, Type type)
        {
            using (FileStream file = File.Open(path, FileMode.Open, FileAccess.Read))
            {
                object ret = new System.Xml.Serialization.XmlSerializer(type).Deserialize(file);
                file.Close();
                return ret;
            }
        }

		/// <summary>
		/// Saves an object as an XML File
		/// </summary>
        public static void SerializeXmlFile(String path, object obj)
        {
            using (FileStream file = File.Open(path, FileMode.Create))
            {
                new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(file, obj);
                file.Close();
            }
        }

		/// <summary>
		/// Attempts multiple times to call DeseriazlizeXmlFile. On each attempt, if an IO exception
		/// is thrown, it will wait 4 seconds then try again, until all the retries have been used.
		/// </summary>
        public static object TryDeserializeXmlFile(String path, Type type, int numRetries)
        {
            Exception e = null;
            for (int i = 0; i < numRetries; i++)
            {
                try
                {
                    object d = DeserialzeXmlFile(path, type);
                    return d;
                }
                catch (IOException ex)
                {
                    e = ex;
                    System.Threading.Thread.Sleep(4000);
                }
            }
            throw new Exception(String.Format("Could not deserialize file {0} after {1} retries", path, numRetries), e);
        }
    }
}
